package com.online.taxi.order.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * @Author:jiangqikun
 * @Date:2022/4/11 20:19
 **/

@Slf4j
@Configuration
public class ZkCoreClientConfig {

    /**
     *     zk 服务端集群地址
     */
    @Value("${zk.url}")
    private String zkUrl;

    @Value("${spring.application.name}")
    private String appName;

    /**
     * session 超时时间
     */
    private int timeOut = 60000;

    /**
     * zkclient 重试间隔时间
     */
    private int baseSleepTimeMs = 5000;

    /**
     * zkclient 重试次数
     */
    private int retryCount = 5;


    /**
     * 使用double-check 创建client
     */
    @Bean
    public CuratorFramework init() {
        CuratorFramework client = CuratorFrameworkFactory
                .builder()
                .connectString(zkUrl)
                .sessionTimeoutMs(timeOut)
                .retryPolicy(new ExponentialBackoffRetry(baseSleepTimeMs, retryCount))
                            .namespace(appName)
                .build();
        // 或者使用工厂模式
        // client = CuratorFrameworkFactory.newClient(zkUrl,new ExponentialBackoffRetry(baseSleepTimeMs,retryCount)).usingNamespace(appName);
        client.start();
        log.info("client is created at ================== {}", LocalDateTime.now());
        return client;
    }

}

